#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

int maxPathSum(TreeNode* root) {
    int res = INT_MIN;
    auto dfs = [&](auto&& dfs, TreeNode* root)->int {
        if (root == nullptr) return 0;
        int l = max(0, dfs(dfs, root->left));
        int r = max(0, dfs(dfs, root->right));
        res = max(res, l + r + root->val);
        return root->val + max(l, r);
    };
    dfs(dfs, root);
    return res;
}